package com.ewzj.bigdata.mvp.ui.fragment;

import android.animation.Animator;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.daimajia.androidanimations.library.Techniques;
import com.daimajia.androidanimations.library.YoYo;
import com.ewzj.bigdata.R;
import com.ewzj.bigdata.app.constants.AppConstants;
import com.ewzj.bigdata.di.component.DaggerCommonComponent;
import com.ewzj.bigdata.di.module.CommonModule;
import com.ewzj.bigdata.mvp.contract.CommonContract;
import com.ewzj.bigdata.mvp.model.entity.resbean.BannerBean;
import com.ewzj.bigdata.mvp.model.entity.resbean.FilterBean;
import com.ewzj.bigdata.mvp.model.entity.resbean.NewBean;
import com.ewzj.bigdata.mvp.model.entity.resbean.TabBean;
import com.ewzj.bigdata.mvp.presenter.CommonPresenter;
import com.ewzj.bigdata.mvp.ui.adapter.BannerViewHolder;
import com.ewzj.bigdata.mvp.ui.adapter.NewsAdapter;
import com.jess.arms.base.BaseFragment;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.widget.CustomPopupWindow;
import com.volokh.danylo.visibility_utils.calculator.DefaultSingleItemCalculatorCallback;
import com.volokh.danylo.visibility_utils.calculator.ListItemsVisibilityCalculator;
import com.volokh.danylo.visibility_utils.calculator.SingleListViewItemActiveCalculator;
import com.volokh.danylo.visibility_utils.scroll_utils.ItemsPositionGetter;
import com.zhouwei.mzbanner.MZBannerView;
import com.zhouwei.mzbanner.holder.MZHolderCreator;
import com.zhouwei.mzbanner.holder.MZViewHolder;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jzvd.JZMediaManager;
import cn.jzvd.JZUtils;
import cn.jzvd.JZVideoPlayer;
import me.relex.circleindicator.CircleIndicator;

import static com.jess.arms.utils.Preconditions.checkNotNull;


public class CommonFragment extends BaseFragment<CommonPresenter> implements CommonContract.View {


    @BindView(R.id.rv_news)
    RecyclerView rvNews;
    @BindView(R.id.swipeRefreshLayout)
    SwipeRefreshLayout swipeRefreshLayout;
    @BindView(R.id.btn_select)
    ImageButton btn_select;
    @BindView(R.id.flowlayout)
    TagFlowLayout flowlayout;
    @BindView(R.id.ll_fifter)
    LinearLayout llFifter;
    private List<NewBean> newBeanList;
    private NewsAdapter newsAdapter;
    private View headerView;
    MZBannerView bannerView;
    CircleIndicator indicator;
    TabBean tabBean;
    Boolean isneedBanner = false;
    CustomPopupWindow window;
    private ListItemsVisibilityCalculator mListItemVisibilityCalculator;
    private ItemsPositionGetter mItemsPositionGetter;
    private int mScrollState;
    List<String> showImageTabs = Arrays.asList("公司", "社会");

    public static CommonFragment newInstance(TabBean tabBean, boolean isneedBanner) {
        CommonFragment fragment = new CommonFragment();
        Bundle args = new Bundle();
        args.putParcelable(AppConstants.FRAGMENT_ARG, tabBean);
        args.putBoolean(AppConstants.ISNEED_BANNER, isneedBanner);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void setupFragmentComponent(AppComponent appComponent) {
        DaggerCommonComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .commonModule(new CommonModule(this))
                .build()
                .inject(this);
    }

    @Override
    public View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_common, container, false);
    }

    private void initHeaderView() {
        if (headerView == null) {
            headerView = LayoutInflater.from(getActivity()).inflate(R.layout.banner_view, null, false);
            bannerView = headerView.findViewById(R.id.banner);
            indicator = headerView.findViewById(R.id.indicator);
            bannerView.setIndicatorVisible(false);
        }
    }

    private void initAdapter() {
        if (newBeanList == null) {
            newBeanList = new ArrayList<>();
        }
        if (newsAdapter == null) {
            newsAdapter = new NewsAdapter(newBeanList);
            if (isneedBanner) {
                newsAdapter.addHeaderView(headerView);
            }
        }
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
        rvNews.setLayoutManager(mLayoutManager);
        rvNews.setAdapter(newsAdapter);

        newsAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                mPresenter.loadmoredata();
            }
        }, rvNews);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        if (getArguments() != null) {
            tabBean = (TabBean) getArguments().getParcelable(AppConstants.FRAGMENT_ARG);
            isneedBanner = TextUtils.isEmpty(tabBean.getBannerurl()) ? false : true;
        }
        if (showImageTabs.contains(tabBean.getName())) {
            btn_select.setVisibility(View.VISIBLE);
        } else {
            btn_select.setVisibility(View.GONE);
        }
        if (isneedBanner) {
            initHeaderView();
        }
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mPresenter.refrehdata();
            }
        });
        initAdapter();
        if (newsAdapter.getData().size() == 0&&tabBean!=null) {
            if (isneedBanner) {
                mPresenter.getbannerData(tabBean.getId());
            }
            mPresenter.getInitData(newBeanList);
        }

    }

    @Override
    public void onDestroyView() {
        rvNews.removeAllViews();
        super.onDestroyView();
    }

    @Override
    public void loadBannerView(List<BannerBean> newBeans) {
        bannerView.setPages(newBeans, new MZHolderCreator() {
            @Override
            public MZViewHolder createViewHolder() {
                return new BannerViewHolder();
            }
        });
        indicator.setViewPager(bannerView.getViewPager());
//
    }

    @Override
    public void notifyNewsAdd(List<NewBean> newBeans) {
        newsAdapter.addData(newBeans);
    }

    /**
     * 此方法是让外部调用使fragment做一些操作的,比如说外部的activity想让fragment对象执行一些方法,
     * 建议在有多个需要让外界调用的方法时,统一传Message,通过what字段,来区分不同的方法,在setData
     * 方法中就可以switch做不同的操作,这样就可以用统一的入口方法做不同的事
     * <p>
     * 使用此方法时请注意调用时fragment的生命周期,如果调用此setData方法时onCreate还没执行
     * setData里却调用了presenter的方法时,是会报空的,因为dagger注入是在onCreated方法中执行的,然后才创建的presenter
     * 如果要做一些初始化操作,可以不必让外部调setData,在initData中初始化就可以了
     *
     * @param data
     */

    @Override
    public void setData(Object data) {

    }


    @Override
    public void showLoading() {
        swipeRefreshLayout.setRefreshing(true);
    }

    @Override
    public void hideLoading() {
        swipeRefreshLayout.setRefreshing(false);
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {

    }

    @Override
    public void onPause() {
        super.onPause();
        if (bannerView != null) {
            bannerView.pause();//暂停轮播
        }

        JZVideoPlayer.releaseAllVideos();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (bannerView != null) {
            bannerView.start();//开始轮播
        }
    }

    @Override
    public BaseQuickAdapter obtainAdapter() {
        if (newsAdapter == null) {
            newsAdapter = new NewsAdapter(newBeanList);
        }
        return newsAdapter;
    }

    @Override
    public void refreshNewsChange(List<NewBean> newBeans) {
        if (newsAdapter == null) {
            return;
        }
        newsAdapter.setNewData(newBeans);
    }

    @Override
    public TabBean obtainCurrentTab() {
        if (tabBean == null) {

        }
        return tabBean;
    }


    @OnClick(R.id.btn_select)
    public void onViewClicked() {
        if (tabBean != null) {
            mPresenter.loadFilterData(tabBean.getId());
        }
    }

    @Override
    public void popwindowShow(List<FilterBean> filterBeans) {
        flowlayout.setAdapter(new TagAdapter<FilterBean>(filterBeans) {
            @Override
            public View getView(FlowLayout parent, int position, FilterBean filterBean) {
                TextView textView= (TextView) View.inflate(getActivity(),R.layout.text_tag_item,null);
                textView.setText(filterBean.getName());
                return textView;
            }
        });
        llFifter.setVisibility(View.VISIBLE);
        YoYo.with(Techniques.SlideInUp)
                .duration(700)
                .repeat(0)
                .withListener(new Animator.AnimatorListener() {
                    @Override
                    public void onAnimationStart(Animator animator) {
                        btn_select.setVisibility(View.GONE);
                    }

                    @Override
                    public void onAnimationEnd(Animator animator) {

                    }

                    @Override
                    public void onAnimationCancel(Animator animator) {

                    }

                    @Override
                    public void onAnimationRepeat(Animator animator) {

                    }
                })
                .playOn(llFifter);
    }



    @OnClick({R.id.tv_dismiss, R.id.tv_confirm})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_dismiss:
                YoYo.with(Techniques.SlideOutDown)
                        .duration(700)
                        .repeat(0)
                        .withListener(new Animator.AnimatorListener() {
                            @Override
                            public void onAnimationStart(Animator animator) {

                            }

                            @Override
                            public void onAnimationEnd(Animator animator) {
                                btn_select.setVisibility(View.VISIBLE);
                                llFifter.setVisibility(View.GONE);
                            }

                            @Override
                            public void onAnimationCancel(Animator animator) {

                            }

                            @Override
                            public void onAnimationRepeat(Animator animator) {

                            }
                        })
                        .playOn(llFifter);
                break;
            case R.id.tv_confirm:
                ArmsUtils.snackbarText("选中筛选");
                break;
        }
    }
}
